<?php
/**
 * Created by PhpStorm.
 * User: ZhangYi
 * Date: 2011-1-13
 * Time: 14:14:47
 * To change this template use File | Settings | File Templates.
 */

class IEasySearch
{
    static public function getLuceneIndex($target)
    {
        ProjectConfiguration::registerZend();

        if (file_exists($index = self::getLuceneIndexFile($target))) {
            return Zend_Search_Lucene::open($index);
        }
        else
        {
            return Zend_Search_Lucene::create($index);
        }

    }

    static public function getLuceneIndexFile($target)
    {
        return sfConfig::get('sf_data_dir') . '/search_' . $target . "_" . sfConfig::get('sf_environment') . '.index';
    }


    static public function getBestFragment($input, $query, $limit)
    {
        $fragment = "";

        $input = self::getContentWithOutHtmlTags($input);
        $stopChars = array(".", "。", "，", " ");
        if (($pos = mb_strpos($input, $query, null, 'utf-8')) !== FALSE) {
            $querylen = mb_strlen($query, 'utf-8');
            if ($pos < $limit) {
                $fragment = mb_substr($input, 0, $limit, 'utf-8');
            } else {

                $firstHalf = mb_substr($input, 0, $pos, 'utf-8');
                //            $secondHalf = mb_substr($input, $pos, mb_strlen($input, 'utf-8'), 'utf-8');

                $stopPos = 0;
                foreach ($stopChars as $stop)
                {
                    $tmp = mb_strrpos($firstHalf, $stop, null, 'utf-8');
                    if ($tmp > $stopPos) {
                        $stopPos = $tmp;
                    }
                }
                if ($pos - $stopPos < $limit) {
                    $fragment = mb_substr($input, $stopPos + 1, $limit, 'utf-8');
                } else
                {
                    $fragment = mb_substr($input, $pos, $limit, 'utf-8');
                }

            }

            $posInFragment = mb_strpos($fragment, $query, null, 'utf-8');
            $fragment = mb_substr($fragment, 0, $posInFragment, "utf-8") . "<b style='color: black; background-color: rgb(102, 255, 255);'>" .
                        mb_substr($fragment, $posInFragment, $querylen, 'utf-8') . "</b>"
                        . mb_substr($fragment, $posInFragment + $querylen, mb_strlen($fragment, 'utf-8') - $posInFragment - $querylen, 'utf-8');
        } else
        {
            return "";
        }


        return $fragment . "...";
    }


    static public function customHighlight($input, $query)
    {

    }


    static public function getContentWithOutHtmlTags($inputHtml)
    {
        $resource = preg_replace("/<script.*>.*<\/script>/siU", "", $inputHtml);
        //        $resource = preg_replace("&nbsp", "", $resource);
        $resource = strip_tags($resource);
        return $resource;
    }
}
